package com.cx.controller.admin.basic;

import java.io.InputStream;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cx.base.ApiModel;
import org.cx.base.BaseController;
import org.cx.entity.PageData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cx.service.admin.basic.UploadManager;

@RestController("admin/basic/upload")
@RequestMapping("admin/basic/upload")
public class UploadController  extends BaseController {

    @Resource
    private UploadManager uploadService;
    
    //导入模板
    @GetMapping("/getTemplate/**")
    public String uploadTemplate(HttpServletRequest request,HttpServletResponse response) throws Exception {

        String servletPath = request.getServletPath();
		String imageName = servletPath.replaceFirst("/admin/basic/upload/getTemplate/", "");
		
		InputStream stream = getClass().getClassLoader().getResourceAsStream("template/"+imageName);
        
        ServletOutputStream out = null;
		try {
			response.setContentType("application/vnd.ms-excel");
			out = response.getOutputStream();
			//读取文件流
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = stream.read(buffer)) != -1){
				out.write(buffer,0,len);
			}
			
			out.flush();
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			out.close();
			stream.close();
		}
		return null;
    }

    @ResponseBody
    @RequestMapping(value = "/saveExcelInfo")
    public ApiModel saveExcelInfo(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) throws Exception {
        PageData pd = this.getPageData();
        pd.put("user",getUserByToken());
        Integer result  = uploadService.saveExcelObjectIntoTable(pd,file);
        if(result<=0){
            return buildErrorMsg(null,DATA_ERROR,FAIL);
        }
        return buildSuccMsg(null);
    }


}
